import React, { useState, useEffect } from 'react';
import { TjFilter, TjHeader, TjContent, TjModal, TjModalTitle } from '@/tjComponents';
import { useRequestPowerAfterInit } from '@/hooks/useRequestPowerAfterInit';
import { Select, DatePicker, Button, Drawer, message } from 'antd';
import Xj from './components/Xj';
import moment from 'moment';
import { useSetState } from 'ahooks';
import type { StationType, ProvinceType } from '@/hooks/useRequestPowerAfterInit';
import _ from 'lodash';
import { useForm } from 'antd/lib/form/Form';
import XjAddModalContent from './components/XjAddModalContent';
import { queryDefaultTemplate } from './services';
import { HttpCode } from '#/utils/contacts.js';
import './index.less';
import { FileTextOutlined } from '@ant-design/icons';
import DeclarationOverview from './components/DeclarationOverview';
import { connect } from 'umi';

const disabledDate = (current: any) => {
  return current && current < moment().add(1, 'days').endOf('day');
};

const DailyRollingTrade: React.FC<IDailyRollingTradeProps> = (props) => {
  const [defaultValue, setDefaultValue] = useSetState<any>({});
  const { initLoading, province, errorMsg, treeData } = useRequestPowerAfterInit(
    `/power/dataPower/common/${props.menuCode}/t_station`,
    (parmas) => {
      setInitFilterValues(parmas);
    },
    {
      convertResult: '1',
      matchFirst: (arr) => {
        return _.find(arr, (n: any) => n.value === 'PXBXJ');
      },
    },
  );
  const [stationsOptions, setStationsOptions] = useState<StationType[]>([]);
  const [filterValues, setFilterValues] = useState<any>();
  const [templateData, setTemplateData] = useState<any[]>([]);
  const [isRefresh, setIsRefresh] = useState<number>();
  const [loading, setLoading] = useState<boolean>(false);
  const [visible, setVisible] = useState<boolean>(false);

  const [form] = useForm();

  const setInitFilterValues = (firstProvince: ProvinceType) => {
    const stations: StationType[] = firstProvince.stations;
    const defaultFilterValues = {
      marketId: firstProvince.value,
      stationId: stations[0].stationId,
      startDate: moment().add(2, 'day'),
    };
    setDefaultValue(defaultFilterValues);
    setFilterValues(defaultFilterValues);
    setStationsOptions(stations);
  };

  const changeMarketId = (value: string) => {
    const currentProvinceInfo = _.find(province, (n: any) => n.value === value);
    const stations = _.get(currentProvinceInfo, 'stations', []);
    form.setFieldsValue({ stationId: stations[0].stationId });
    setStationsOptions(stations);
  };

  const onSearch = (values: any) => {
    setFilterValues(values);
  };

  const onReset = (values: any) => {
    const { marketId } = values;
    const currentProvinceInfo = _.find(province, (n: any) => n.value === marketId);
    const stations = _.get(currentProvinceInfo, 'stations', []);
    setStationsOptions(stations);
    setFilterValues(values);
  };

  const add = () => {
    if (templateData.length <= 0) {
      return message.warning('暂无查询到新增模板数据');
    }
    TjModal.open({
      title: <TjModalTitle title="新增" />,
      destroyOnClose: true,
      maskClosable: false,
      content: (
        <XjAddModalContent
          templateData={templateData}
          filterValues={filterValues}
          stationsOptions={stationsOptions}
        />
      ),
      width: 1200,
      onOk: () => {
        setIsRefresh(new Date().valueOf());
      },
    });
  };

  const queryTemplate = (marketId: string, startDate: string) => {
    queryDefaultTemplate({ marketId, startDate }).then((res: any) => {
      if (res.statusCode === HttpCode.SUCCESS) {
        const dataList = _.get(res, 'data.dataList', []);
        setTemplateData(dataList);
      }
    });
  };

  const changeLoading = (type: boolean) => {
    setLoading(type);
  };

  useEffect(() => {
    if (filterValues) {
      const { marketId, stationId, startDate } = filterValues;
      if (marketId && startDate) {
        queryTemplate(marketId, startDate.format('YYYY-MM-DD'));
      }
    }
  }, [filterValues]);

  return (
    <div className="daily-rolling-trade">
      <TjHeader
        left={
          <TjFilter
            defaultValues={defaultValue}
            form={form}
            items={[
              {
                name: 'marketId',
                render: (
                  <Select
                    options={province}
                    style={{ width: 180 }}
                    onChange={changeMarketId}
                    loading={initLoading}
                  />
                ),
              },
              {
                name: 'stationId',
                render: (
                  <Select style={{ width: 180 }} loading={initLoading}>
                    {stationsOptions.map((item) => (
                      <Select.Option key={item.stationId} value={item.stationId}>
                        {item.stationName}
                      </Select.Option>
                    ))}
                  </Select>
                ),
              },
              {
                name: 'startDate',
                render: <DatePicker disabledDate={disabledDate} />,
              },
            ]}
            onSearch={onSearch}
            onReset={onReset}
            loading={initLoading || loading}
          />
        }
        right={
          <Button
            icon={<FileTextOutlined />}
            loading={initLoading || loading}
            type="link"
            onClick={() => setVisible(true)}
          >
            申报总览
          </Button>
        }
      />
      <TjContent
        titleLeft="月内合同申报"
        titleRight={
          <Button onClick={add} type="link" loading={initLoading || loading}>
            新增
          </Button>
        }
      >
        <Xj filterValues={filterValues} isRefresh={isRefresh} changeLoading={changeLoading} />
      </TjContent>

      <Drawer
        title={<TjModalTitle title="申报总览" />}
        onClose={() => setVisible(false)}
        visible={visible}
        width={1200}
        destroyOnClose
      >
        <DeclarationOverview stationsOptions={stationsOptions} filterValues={filterValues} />
      </Drawer>
    </div>
  );
};

interface IDailyRollingTradeProps {
  menuCode: string;
}

export default connect(({ global }: any) => ({
  menuCode: global.configure.menuCode,
}))(DailyRollingTrade);
